package com.portme.client.pages.widgets;

import java.util.HashMap;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.portme.shared.ClientCustomTab;
import com.portme.shared.ClientPost;

public class SideBar extends VerticalPanel{
	
	private ClientCustomTab currentTab;
	private PostDisplayWidget postDisplay;
	private HashMap<Long, PostLink> linksMap = new HashMap<Long, PostLink>();
	private PostLink selectedLink = null;
	
	public SideBar(ClientCustomTab tab) {
		this.currentTab = tab;
		//createWidget();
	}
	
	public void setDisplayWidget(PostDisplayWidget displayWidget) {
		this.postDisplay = displayWidget;
	}

	public void createWidget(final String user) {
		if(currentTab != null) {
			if(currentTab.getPosts() != null && !currentTab.getPosts().isEmpty()) {
				linksMap.clear();
				for(final ClientPost post : currentTab.getPosts()) {
					ClickHandler clickHandler = new ClickHandler() {
						
						@Override
						public void onClick(ClickEvent event) {
							History.newItem(""+user+"/"+currentTab.getId()+"/"+post.getId(), false);
							postDisplay.showPost(post);
						}
					};
					PostLink postLink = new PostLink(post, clickHandler);
					this.add(postLink);
					linksMap.put(post.getId(), postLink);
				}
			}
			
		}
	}
	
	public void selectPost(Long selectedPostId) {
		ClientPost selectedPost = currentTab.getPost(selectedPostId);
		if(selectedPost != null) {
			postDisplay.showPost(selectedPost);
			if(selectedLink != null) {
				selectedLink.deselect();
			}
			selectedLink = linksMap.get(selectedPostId);
			if(selectedLink != null) {
				selectedLink.select();
			}
		}
	}
	
	public void selectFirst(String user) {
		ClientPost selectedPost = null;
		if(!currentTab.getPosts().isEmpty()) {
			selectedPost = currentTab.getPosts().get(0);
		}
		if(selectedPost != null) {
//			History.newItem(""+user+"/"+currentTab.getId()+"/"+selectedPost.getId(), false);
			postDisplay.showPost(selectedPost);
			if(selectedLink != null) {
				selectedLink.deselect();
			}
			selectedLink = linksMap.get(selectedPost.getId());
			if(selectedLink != null) {
				selectedLink.select();
			}
		}
	}
	
	public void addPost(final String user, final ClientPost post) {
		if(currentTab != null) {
			if(post != null) {
				ClickHandler clickHandler = new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						History.newItem(""+user+"/"+currentTab.getId()+"/"+post.getId(), false);
						postDisplay.showPost(post);
					}
				};
				PostLink postLink = new PostLink(post, clickHandler);
				this.add(postLink);
				linksMap.put(post.getId(), postLink);
				currentTab.addPost(post);
				selectPost(post.getId());
			}
			
		}
	}
	
}
